package com.imoocdl.service.impl;

import com.imoocdl.dto.OrderDtDTO;
import com.imoocdl.enums.ResultEnum;
import com.imoocdl.exception.SellException;
import com.imoocdl.repository.OrderMasterRepository;
import com.imoocdl.service.BuyerService;
import com.imoocdl.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by pc on 2018/7/18.
 */
@Service
@Slf4j
public class BuyerServiceImpl implements BuyerService {
    @Autowired
    private OrderService orderService;
    @Override
    public OrderDtDTO findOrderOne(String openid, String orderId) {
        return checkOrder(openid, orderId);
    }

    @Override
    public OrderDtDTO cancelOrder(String openid, String orderId) {
        OrderDtDTO orderDtDTO = checkOrder( openid,  orderId);
        if(orderDtDTO == null){
            log.error("[取消订单] 该订单不存在");
            throw new SellException(ResultEnum.ORDER_NOT_EXIST);
        }
        return orderService.cancel(orderDtDTO);
    }

    private OrderDtDTO checkOrder(String openid, String orderId){
        OrderDtDTO orderDtDTO = orderService.findOne(orderId);
        if(orderDtDTO == null){
            return null;
        }
        //判断openid是否是自己的订单
        if(!orderDtDTO.getBuyerOpenid().equals(openid)){
            log.error("[查询订单] 订单的openid不一致 openid={},orderId={}",openid,orderId);
            throw new SellException(ResultEnum.ORDER_OWNER_ERROR);
        }
        return orderDtDTO;
    }
}
